/* eslint-disable react-hooks/rules-of-hooks */
import React, { useEffect, useState } from 'react'
import { Role, Root } from '@/types'
import { Space, Table } from 'antd'
import { setId, setMenuList } from '@/store/modules/user'

import { useAppDispatch } from '@/store/hooks'
import { useNavigate } from 'react-router-dom'
import { usePermissionsList } from '@/api/query'

const { Column } = Table
const index: React.FC = () => {
  const [PermissionsData, setPermissionsData] = useState<Role[]>([])
  const { isError, isLoading, data, error } = usePermissionsList()
  const dispatch = useAppDispatch()
  const navigate = useNavigate()
  useEffect(() => {
    if (data) {
      const dataSource = data?.map((item: Role) => ({
        ...item,
        key: item._id
      }))
      setPermissionsData(dataSource)
    }
  }, [data])
  if (isError) {
    console.log(error)

    return <div>请求错误</div>
  }
  if (isLoading) {
    return <div>加载中</div>
  }
  const distributeRole = (Menus: Root, id: string) => {
    navigate('/roleUpdate')
    dispatch(setMenuList(Menus))
    dispatch(setId(id))
  }
  return (
    <div>
      <Table dataSource={PermissionsData}>
        <Column
          title="编号"
          key="firstName"
          render={(_: any, record: Role) => (
            <span>{record._id.slice(10, 12)}</span>
          )}
        />
        <Column title="角色名称" dataIndex="RoleName" key="RoleName" />
        <Column title="描述" dataIndex="Description" key="Description" />
        <Column
          title="用户数"
          key="addTime"
          render={(_: any, record: Role) => (
            <span>{record.UserIds.length}</span>
          )}
        />
        <Column
          title="注册时间"
          key="addTime"
          render={(_: any, record: Role) => (
            <span>{new Date(record.AddTime).toLocaleString()}</span>
          )}
        />
        <Column
          title="操作"
          key="action"
          render={(_: any, record: Role) => (
            <Space size="middle">
              <a
                type="primary"
                onClick={() => distributeRole(record.MenuList, record._id)}
              >
                分配角色
              </a>
            </Space>
          )}
        />
      </Table>
    </div>
  )
}

export default index
